package org.lanqiao.userprofile.movie.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketServer extends TextWebSocketHandler {
    private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = extractUserId(session);
        sessions.put(userId, session);
        System.out.println("新的WebSocket连接已建立，用户ID: " + userId);
    }

    private String extractUserId(WebSocketSession session) {
        String userId = session.getUri().getQuery().replace("userId=", "");
        return userId;
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String receivedMessage = message.getPayload();
        System.out.println("接收到消息：" + receivedMessage);

        String responseMessage = "收到并处理了消息：" + receivedMessage;
        sendMessageToAll(responseMessage);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        //System.out.println("WebSocket连接已关闭，Session ID: " + session.getId());
    }

    public void sendMessageToAll(Set<String> set, String message) {

        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            String key = entry.getKey();
            WebSocketSession value = entry.getValue();
            System.out.println("Key: " + key);
            try {
                if (set.contains(key)) {
                    System.out.println("推送的Key: " + key);
                    value.sendMessage(new TextMessage(message));
                }
            } catch (IOException e) {
                System.out.println("发送消息失败：" + e.getMessage());
            }
        }

    }

    public void sendMessageToAll(String message) {

        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            String key = entry.getKey();
            WebSocketSession value = entry.getValue();
            System.out.println("Key: " + key);
            try {
                value.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                System.out.println("发送消息失败：" + e.getMessage());
            }
        }
    }
}
